package com.lesserpand.springcloudalibabacore.config.redis.redissonlock.service.impl;

import com.lesserpand.springcloudalibabacore.config.rabbitmq.utils.ProviderUtils;
import com.lesserpand.springcloudalibabacore.config.redis.constant.RedisEnum;
import com.lesserpand.springcloudalibabacore.config.redis.redissonlock.service.SkillService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bailuo
 * @version 2.0
 * @Description 模拟抢购，分布式锁使用redisson
 * @Date Created in 2019/1/14 17:47
 */
@Service("skillService")
public class SkillServiceImpl implements SkillService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SkillServiceImpl.class);

    @Autowired
    private ProviderUtils providerUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 模拟配置抢购商品，放入redis，理论上需要配置抢购活动的，分布式定时任务，后期处理
     *
     * @param proId   抢购商品id
     * @param skillId 抢购id
     * @param num     抢购数量
     * @return
     */
    @Override
    public String initSkill(Long proId, Long skillId, String num) {
        String key = RedisEnum.SKILL_KEY.getValue() + skillId + ":" + proId;
        stringRedisTemplate.opsForValue().set(key, num, 60, TimeUnit.MINUTES);
        LOGGER.info("缓存成功");
        return "缓存成功";
    }

    /**
     * 抢购商品，查询redis，存在抢购商品，通过rabbitmq下单
     *
     * @param userId  用户id
     * @param skillId 抢购id
     * @param proId   抢购商品id
     * @return
     */
    @Override
    public String skill(Long userId, Long skillId, Long proId) {
        String lockKey = RedisEnum.LOCK_KEY.getValue() + skillId + ":" + proId;
        String key = RedisEnum.SKILL_KEY.getValue() + skillId + ":" + proId;
        // 分布式锁
        RLock lock = redissonClient.getLock(lockKey);
        String retMsg = null;
        try {
            // 加锁代码
            lock.lock();
            String orderNum = stringRedisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(orderNum)) {
                Integer num = Integer.valueOf(orderNum);
                if (num == 0) {
                    LOGGER.error("没有抢购到！");
                    retMsg = "没有抢购到！";
                } else {
                    LOGGER.error("恭喜您抢购成功！通过rabbitmq进行排队订单入库，减少db压力" + Thread.currentThread().getId());
                    providerUtils.send("skill.exchange", "skill.message.queue", userId + "," + proId);
                    retMsg = "恭喜您抢购成功！";
                    // 抢购数量减1
                    stringRedisTemplate.opsForValue().decrement(key);
                }
            } else {
                LOGGER.error("没有抢购到！");
                retMsg = "没有抢购到！";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return retMsg;
    }
}
